package com.fanxuankai.boot.canal.listener;

import com.fanxuankai.boot.canal.listener.annotation.CanalTable;
import com.fanxuankai.boot.canal.listener.autoconfigure.CanalListenerProperties;
import com.google.common.base.CaseFormat;
import org.springframework.core.annotation.AnnotationUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author fanxuankai
 */
public class CanalTableCache {
    @Resource
    private CanalListenerProperties properties;
    private static final Map<Class<?>, TableInfo> TABLE_INFO_CACHE = new HashMap<>();

    public TableInfo getTableInfo(Class<?> domainType) {
        TableInfo tableInfo = TABLE_INFO_CACHE.get(domainType);
        if (tableInfo == null) {
            tableInfo = Optional.ofNullable(AnnotationUtils.findAnnotation(domainType, CanalTable.class))
                    .map(canalTable -> new TableInfo(canalTable.schema(), canalTable.name()))
                    .orElseGet(() -> new TableInfo(properties.getGlobalSchema(),
                            CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, domainType.getSimpleName())));
            TABLE_INFO_CACHE.put(domainType, tableInfo);
        }
        return tableInfo;
    }
}
